package com.example.androidproject.service.config;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;

import com.example.androidproject.service.TimersService;
import com.hyg.common.utils.LogUtils;

/**
 * FileName: ServiceManager
 * Author: huangyuguang
 * Date: 2022/5/12
 */
public class ServiceManager {

    private static ServiceManager instance;

    private Context mContext;
    private TimersService timersService;

    private static final long HEART_BEAT_RATE = 10 * 1000;//每隔10s发送空消息保持WebSocket长连接

    public static ServiceManager getInstance(){
        if(instance == null){
            synchronized (ServiceManager.class){
                if(instance == null){
                    instance = new ServiceManager();
                }
            }
        }
        return instance;
    }

    private void init(Context context){
        this.mContext = context;
        startService(mContext);
    }

    private Handler socketHandler = new Handler();

    private Runnable webSocketRunnable = new Runnable() {
        @Override
        public void run() {
//            if (mWebSocketService != null && mWebSocketService.client != null && mWebSocketService.client.isOpen()) {
//                try {
//                    String heartbeat = "[\"\\n\"]";
//                    LogUtils.e("WebSocketService", "心跳：" + heartbeat);
//                    mWebSocketService.sendMsg(heartbeat,true);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
            //每隔一定的时间，对长连接进行一次心跳检测
            socketHandler.postDelayed(this, HEART_BEAT_RATE);
        }
    };

    /**
     * 重新开始计时
     */
    private void startHeartBeat(){
        if(timersService == null){
            startService(mContext);
        }else {
            timersService.startTimer();
        }
    }

    /**
     * 开启并绑定Timer服务
     */
    public void startService(Context context) {
        Intent bindIntent = new Intent(context, TimersService.class);
        context.startService(bindIntent);
        context.bindService(bindIntent, serviceConnection, context.BIND_AUTO_CREATE);

        socketHandler.removeCallbacks(webSocketRunnable);
        socketHandler.postDelayed(webSocketRunnable, HEART_BEAT_RATE);//开启心跳检测
    }

    /**
     * 停止Timer服务
     */
    public void stopService(Context context) {
        try{
            Intent bindIntent = new Intent(context, TimersService.class);
            context.stopService(bindIntent);
            context.unbindService(serviceConnection);

            socketHandler.removeCallbacks(webSocketRunnable);
        }catch (Exception e){}
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            //服务与活动成功绑定
            timersService = ((TimersService.TimersClientBinder) iBinder).getService();
            LogUtils.e("Service", "Timer服务与context成功绑定");
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            //服务与活动断开
            timersService = null;
            LogUtils.e("Service", "Timer服务与context成功断开");
        }
    };

    public void release(){
        stopService(mContext);
    }
}
